package com.copa.gameStore.application.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.copa.gameStore.application.GameNewsApplicationService;
import com.copa.gameStore.domain.GameNews;
import com.copa.gameStore.domain.GameNewsDetail;
import com.copa.gameStore.dto.GameNewsSearchDto;
import com.copa.gameStore.mapper.GameNewsDetailMapper;
import com.copa.gameStore.mapper.GameNewsMapper;
import com.copa.gameStore.service.GameNewsDetailService;
import com.copa.gameStore.service.GameNewsService;
import com.copa.gameStore.vo.GameNewsDetailVo;
import com.copa.gameStore.vo.ResponseVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.TreeMap;

/**
 * @author copa
 * @createDate 2022-09-25 21:29
 * @function
 */
@Service
public class GameNewsApplicationServiceImpl implements GameNewsApplicationService {

    @Resource
    private GameNewsService gameNewsService;

    @Resource
    private GameNewsDetailService gameNewsDetailService;

    @Resource
    private GameNewsMapper gameNewsMapper;

    @Resource
    private GameNewsDetailMapper gameNewsDetailMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void gameNewsTask() {
        gameNewsService.add();
        gameNewsDetailService.add();
    }

    @Override
    public ResponseVo<GameNewsDetailVo> get(Long id) {
        return ResponseVo.success(GameNewsDetailVo.builder()
                .gameNews(gameNewsMapper.selectById(id))
                .gameNewsDetail(gameNewsDetailMapper.selectOne(new QueryWrapper<GameNewsDetail>().eq("game_news_id", id)))
                .build());
    }

    @Override
    public ResponseVo<TreeMap<LocalDate,List<GameNews>>> getByYearMonth(GameNewsSearchDto gameNewsSearchDto) {
        List<GameNews> gameNewsList = gameNewsMapper.selectByYearMonth(gameNewsSearchDto);
        TreeMap<LocalDate,List<GameNews>> map = new TreeMap<>();
        for (GameNews gameNews : gameNewsList) {
            if (Objects.isNull(map.get(gameNews.getSaleTime()))) {
                map.put(gameNews.getSaleTime(), new ArrayList<>());
            }
            map.get(gameNews.getSaleTime()).add(gameNews);
        }
        return ResponseVo.success(map);
    }
}
